package com.paomi.client.activity.detail.presenter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.hannesdorfmann.mosby3.mvp.MvpBasePresenter;
import com.paomi.client.R;
import com.paomi.client.activity.detail.OrderDetailView;
import com.paomi.client.activity.detail.model.OrderDeatilBean;
import com.paomi.client.activity.detail.model.SendDetailBean;
import com.paomi.client.activity.pay.model.AddressBean;
import com.paomi.client.activity.payMoney.model.PayMoneyBean;
import com.paomi.client.activity.payResult.ResultPayActivity;
import com.paomi.client.bean.BaseJSON;
import com.paomi.client.bean.DictBean;
import com.paomi.client.fragment.order.model.OrderListBean;
import com.paomi.client.net.Api;
import com.paomi.client.net.BaseCallback;
import com.paomi.client.net.Constants;
import com.paomi.client.utils.PayResult;
import com.paomi.client.utils.PayUtil;
import com.paomi.client.utils.ToastUtil;
import com.paomi.client.widget.RxToast;
import com.paomi.client.widget.StarBar;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import retrofit2.Call;

/**
 *
 */
public class OrderDetailPre extends MvpBasePresenter<OrderDetailView> {
    /**
     * 获取订单交易的详情
     *
     * @param orderId
     */
    public void getOrderDetail(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).myOrderDetail(orderId).enqueue(new BaseCallback<OrderDeatilBean>() {
            @Override
            public void onResponse(Call<OrderDeatilBean> call, OrderDeatilBean result) {
                if(isViewAttached()) {
                    getView().setOrderDetailData(result);
                }
            }
        });
    }

    /**
     * 获取订单交易的收货地址
     *
     * @param orderId
     */
    public void getOrderDetailAddress(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).myOrderDetailAddress(orderId).enqueue(new BaseCallback<AddressBean>() {
            @Override
            public void onResponse(Call<AddressBean> call, AddressBean result) {
                if(isViewAttached())
                    getView().setOrderDetailAddress(result);
            }
        });
    }

    /**
     * 获取订单交易的快递信息
     *
     * @param orderId
     */
    public void getOrderSend(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).myOrderDetailSend(orderId).enqueue(new BaseCallback<SendDetailBean>() {
            @Override
            public void onResponse(Call<SendDetailBean> call, SendDetailBean result) {
                getView().setOrderSend(result);
            }
        });
    }

    /**
     * 确认收货的操作
     *
     * @param activity
     */
    public void sureBtn(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.received_success));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.sure_order));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrderConfim(id);
            }
        });
    }

    /**
     * 用户-订单-确认收货
     *
     * @param orderId
     */
    public void getOrderConfim(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).orderConfirm(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage = "确认收货";
                getView().setOrderSure(result);
            }
        });
    }

    /**
     * 订单删除的操作
     *
     * @param activity
     */
    public void deleteBtn(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.del_order));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.delete_order));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setText(activity.getResources().getString(R.string.no_btn));
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setText(activity.getResources().getString(R.string.yes_btn));
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrderDelete(id);
            }
        });
    }

    /**
     * 用户-订单-删除
     *
     * @param orderId
     */
    public void getOrderDelete(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).orderDelete(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage = "订单删除";
                getView().setOrderSure(result);
            }
        });
    }

    /**
     * 订单取消的操作
     *
     * @param activity
     */
    public void deleteCancel(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.clear_order));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.cancel_order));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setText(activity.getResources().getString(R.string.no_btn));
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setText(activity.getResources().getString(R.string.yes_btn));
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getOrderCancel(id);
            }
        });
    }

    /**
     * 用户-订单-取消
     *
     * @param orderId
     */
    public void getOrderCancel(String orderId) {
        Api.getInstanceService(Constants.Ticket_URL).orderCancel(orderId).enqueue(new BaseCallback<BaseJSON>() {
            @Override
            public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                result.returnMessage = "订单取消";
                getView().setOrderSure(result);
            }
        });
    }

    /**
     * 获取字典
     */
    public void getDict() {
        Api.getInstanceService(Constants.BASE_URL).getDict("GOODS_COOLECT_TICKET_TYPE").enqueue(new BaseCallback<DictBean>() {
            @Override
            public void onResponse(Call<DictBean> call, DictBean result) {
                if(isViewAttached()){
                    getView().showDict(result);
                }
            }
        });
    }

    /**
     * 支付订单的操作
     *
     * @param activity
     */
    public void setPayNow(Activity activity, Typeface iconfont, String paySureJson) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.pay_type_layout, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        ButterKnife.bind(dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView chartTv=dialog.findViewById(R.id.chart_tv);
        TextView btnWeChart=dialog.findViewById(R.id.btn_we_chart);
        TextView aliPay=dialog.findViewById(R.id.ali_pay);
        TextView btnAliPay=dialog.findViewById(R.id.btn_aliPay);
        chartTv.setTypeface(iconfont);
        btnWeChart.setTypeface(iconfont);
        aliPay.setTypeface(iconfont);
        btnAliPay.setTypeface(iconfont);
        btnWeChart.setOnClickListener(new View.OnClickListener() {//微信选中
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                btnAliPay.setText(activity.getResources().getString(R.string.uncheck_sex));
                btnAliPay.setTextColor(activity.getResources().getColor(R.color.text_gray_99));
                btnWeChart.setText(activity.getResources().getString(R.string.check_sex));
                btnWeChart.setTextColor(activity.getResources().getColor(R.color.main_color));
                payIsCan(1,""+paySureJson,activity);
            }
        });
        btnAliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                btnWeChart.setText(activity.getResources().getString(R.string.uncheck_sex));
                btnWeChart.setTextColor(activity.getResources().getColor(R.color.text_gray_99));
                btnAliPay.setText(activity.getResources().getString(R.string.check_sex));
                btnAliPay.setTextColor(activity.getResources().getColor(R.color.main_color));
                payIsCan(2,""+paySureJson,activity);
            }
        });

    }

    /**
     * 支付订单接口
     * @param type
     * @param getId
     * orderId	true	订单号
     * type	true	支付类型 1 微信 2 支付宝
     */
    public void payIsCan(int type,String getId,Activity activity){
        mActivity=activity;
        Map<String,String> maps=new HashMap<>();
        maps.put("orderId",getId);
        maps.put("type",""+type);
        Api.getInstanceService(Constants.Pay_URL).sureOrderPay(maps).enqueue(new BaseCallback<PayMoneyBean>() {
            @Override
            public void onResponse(Call<PayMoneyBean> call, PayMoneyBean result) {
                if(type==1){//微信的
                    Map<String,String> map=(Map<String, String>) result.getReturnData();
                    PayUtil.payForWx(activity,null,map);
                }else if(type==2){//支付宝
                    payApi_pay(result.getReturnData().toString(),activity);
                }
            }
        });
    }
    private Activity mActivity;
    /**
     * 支付宝支付
     * @param data
     * @param activity
     */
    public void payApi_pay(String data, Activity activity) {
//        final String payInfo = data.get("action");

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(activity);
                // 调用支付接口，获取支付结果
                Map<String, String>  result = alipay.payV2(data, true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {//支付成功
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                ToastUtil.getToastEmail().ToastShow(mActivity,null,1,R.layout.toast_view,mActivity.getResources().getString(R.string.pay_sure));
                Intent intent=new Intent(mActivity,ResultPayActivity.class);
                mActivity.setResult(2003);
                mActivity.startActivity(intent);
                mActivity.finish();

            } else {//支付失败
                Log.e("支付失败",""+payResult);
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                RxToast.info(mActivity.getResources().getString(R.string.pay_cancel_get));
            }

        };
    };

    /**
     * 评价评分的操作
     * @param activity
     */
    public void setStarComment(Activity activity, String id) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_starbar_show, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        StarBar starBar=view.findViewById(R.id.star_bar);
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Map<String,String> stringMap=new HashMap<>();
                stringMap.put("orderId",id);
                stringMap.put("star",""+starBar.getStarMark());
                stringMap.put("content","");
                Api.getInstanceService(Constants.Ticket_URL).setStarBarComment(stringMap).enqueue(new BaseCallback<BaseJSON>() {
                    @Override
                    public void onResponse(Call<BaseJSON> call, BaseJSON result) {
                        //评分成功的操作
                        BaseJSON baseJSON = new BaseJSON();
                        baseJSON.returnMessage = "评分成功";
                        getView().setOrderSure(baseJSON);
                    }
                });

            }
        });
    }

    /**
     * 延迟收货的操作
     * @param activity
     * @param id
     */
    public void setDelayOrder(Activity activity, String id){
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.dialog_delete_shaow, null);
        final Dialog dialog = new Dialog(activity, R.style.theme_dialog);
        dialog.setContentView(view);
        dialog.show();
        TextView title = view.findViewById(R.id.title);
        title.setText(activity.getResources().getString(R.string.delay_order_get));
        TextView msg_tv = view.findViewById(R.id.msg_tv);
        msg_tv.setText(activity.getResources().getString(R.string.delay_comment_title));
        TextView textCancel = view.findViewById(R.id.btn_qd);
        textCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView textSure = view.findViewById(R.id.btn_success);
        textSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }
}
